package com.kn.common.config.shiro;


import com.kn.common.config.jwt.JWTToken;
import com.kn.common.model.ActiveUser;
import com.kn.sys.dao.PermissionDao;
import com.kn.sys.mapper.UserMapper;
import com.kn.sys.model.User;
import com.kn.sys.model.UserExample;
import com.kn.sys.untils.JWTUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class UserRealm extends AuthorizingRealm {
    @Resource
    private UserMapper userMapper;
    @Resource
    private PermissionDao permissionDao;
    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }
    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        authorizationInfo.addStringPermissions(activeUser.getPermis());
        return authorizationInfo;
    }
    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        if(JWTUtils.isExpire(token)){
            throw new AuthenticationException(" token过期，请重新登入！");
        }
        // 解密获得username，用于和数据库进行对比
        String username = JWTUtils.getUsername(token);

        if (username == null) {
            throw new AuthenticationException(" token错误，请重新登入！");
        }
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(username)
                .andIsdelEqualTo(false);
        List<User> users = userMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(users)) {
            throw new AccountException("账号不存在!");
        }
        User user = users.get(0);
        if (! JWTUtils.verify(token, username, user.getPassword())) {
            throw new AccountException("密码错误!");
        }
        List<String> permission = permissionDao.getPermission(user.getId());
        List<String> collect = permission.stream().filter(p -> {
            return !StringUtils.isEmpty(p);
        }).flatMap(p -> {
            return Stream.of(p.split(","));
        }).collect(Collectors.toList());
        //过滤出url,和用户的权限
        ActiveUser activeUser = new ActiveUser();
        activeUser.setUser(user);
        activeUser.setPermis(collect);
        return new SimpleAuthenticationInfo(activeUser, token, getName());
    }
}
